import {Component, OnInit, ViewChild} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-body',
  templateUrl: './body.component.html',
  styleUrls: [
    './body.component.css',
  ]
})

export class BodyComponent implements OnInit {

  hotMovies: object;
  rateMovies: object;
  typeMovies: Array<object> = new Array<object>(0);
  recommendMovies: Array<object> = new Array<object>(0);
  loadIndex = 0;
  actors: object;
  videoUrl = 'http://file.rs.cn/GROUP00/M00/00/00/wKgBuVvnEiiAIL8HAF_Bxhi9PhA557.mp4';
  lastNews: object;
  showRec = 0;
  showType = 0;

  search(term: string) {
    const promise = new Promise((resolve, reject) => {
      this.http.get('/movie/hot/list/12')
        .toPromise()
        .then(
          res => { // Success
            console.log(res);
            resolve();
          }
        );
    });
    return promise;
  }

  constructor(private http: HttpClient) {
    this.http.get('/movie/hot/list/12').subscribe(result => this.hotMovies = result);
    this.http.get('/movie/rate/list').subscribe(result => this.rateMovies = result);
    this.http.post('/movie/type/list', [1, 2, 3]).subscribe(result => {
      for (const i in result) {
        if (i) {
          const typeArr = shuffleArray(result[i]);
          this.typeMovies.push({name: i, data: typeArr});
        }
      }
      this.loadIndex++;
    });
    this.http.get('/movie/recommend/list').subscribe(result => {
      for (const i in result) {
        if (i) {
          this.recommendMovies.push({name: i, data: result[i]});
        }
      }
      this.loadIndex++;
    });
    this.http.get('/news/last').subscribe(result => {
      this.lastNews = result;
    });
    this.sleep(2000);
    for (let i = 0; i < 1e7; i++) {
      if (this.loadIndex === 2) {
        break;
      }
    }
    this.http.get('/person/2/vo/list?size=3').subscribe(result => this.actors = result);
  }

  sleep(milliseconds) {
    const start = new Date().getTime();
    for (let i = 0; i < 1e7; i++) {
      if ((new Date().getTime() - start) > milliseconds) {
        break;
      }
    }
  }

  @ViewChild('videoPlayer') videoPlayer: any;

  changeMovieUrl() {
    this.videoPlayer.nativeElement.load();
  }

  ngOnInit(): void {
  }

}

export function shuffleArray(arr: Array<object>): Array<object> {
  if (arr === null || arr.length === 0) {
    return new Array<object>(0);
  }
  for (const j in arr) {
    if (j) {
      const rIndex = Math.floor(Math.random() * arr.length);
      const tempObj = arr[j];
      arr[j] = arr[rIndex];
      arr[rIndex] = tempObj;
    }
  }
  return arr;
}
